package com.zhongshengnetwork.rightbe.game.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dd.CircularProgressButton;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.PublishSelectPicPopupWindow;
import com.zhongshengnetwork.rightbe.common.pulluprefresh.xlistview.XListView;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.GameRangeModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LifeRewardModel;
import com.zhongshengnetwork.rightbe.gsonmodel.MyRangeModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class GameRangeActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    private final static String url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.zhongshengnetwork.rightbe";//Constant.HOST+"downapp.do?";
    private final static String content = "好玩又益智，赶紧来体验吧~";
    private List<String> ilist;
    private PublishSelectPicPopupWindow menuWindow;
    private TopBarView topbar;
    private XListView listview;
    private List<GameRangeModel> list;
    private MyAdapter adapter;
    private String appid;
    private int pageindex = 0;
    private final static int pagerecords = 20;
    private boolean isRefresh = false;
    private CircularProgressButton game_range_button;
    private MyRangeModel myRangeModel = null;

    private MyIUiListener mIUiListener = new MyIUiListener();
    class MyIUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            Log.e("TAG","分享成功");
            getShareGold();
        }

        @Override
        public void onError(UiError uiError) {
            Log.e("TAG","分享出错");
        }

        @Override
        public void onCancel() {
            Log.e("TAG","分享取消");
        }

        @Override
        public void onWarning(int i) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_QZONE_SHARE || resultCode == Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, mIUiListener);
            }
        }
    }

    private void getShareGold(){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        String url = "miniapp/"+appid+"/usershare.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                final CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    new Handler().postDelayed(new Runnable(){
                        public void run() {
                            ToastUtil.show(GameRangeActivity.this,commonModel.getMsg());
                        }
                    }, 10);
                }
            }
            @Override
            public void onError(String msg) {

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_range);
        registerBoradcastReceiver();
        appid = getIntent().getStringExtra("appid");
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        game_range_button = (CircularProgressButton)findViewById(R.id.game_range_button);
        game_range_button.setBackgroundColor(getResources().getColor(R.color.limitBackgroundColor));
        game_range_button.setStrokeColor(getResources().getColor(R.color.limitBackgroundColor));
        game_range_button.setText("加载中...");
        list = new ArrayList<GameRangeModel>();
        ilist = new ArrayList<String>();
        ilist.add("分享给微信好友");
        ilist.add("分享到微信朋友圈");
        ilist.add("分享给QQ好友");
        ilist.add("分享到QQ空间");
        //ilist.add("取消");
        listview=(XListView) findViewById(R.id.game_range_listview);
        adapter=new MyAdapter();
        listview.setAdapter(adapter);
        //这里一定不能漏掉
        listview.setPullLoadEnable(true);
        listview.setPullRefreshEnable(false);
        listview.setXListViewListener(new XListView.IXListViewListener() {

            @Override
            public void onRefresh() {
                adapter.notifyDataSetChanged();
                SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss");
                Date date = new Date(System.currentTimeMillis());
                listview.setRefreshTime(sdf.format(date));

            }

            @Override
            public void onLoadMore() {
                getData();
            }
        });
        getData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    public void onClickButton(View view){
        if (myRangeModel != null){
           share(view);
        }
    }

    private void share(View v){
        /*
        menuWindow = new PublishSelectPicPopupWindow(GameRangeActivity.this,itemsOnClick,ilist);
        // 显示窗口
        menuWindow.showAtLocation(v,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        */
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(GameRangeActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : ilist){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which == 1){
                        //分享给微信好友
                        shareToWX(1,url,myRangeModel.getName(),content);
                    }else if (which == 2){
                        //分享到朋友圈
                        shareToWX(0,url,myRangeModel.getName(),content);
                    }else if (which == 3){
                        //分享到qq
                        shareToQQ(0,url,myRangeModel.getName(),content);
                    }else if (which == 4){
                        //qq空间
                        shareToQQ(1,url,myRangeModel.getName(),content);
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    //分享到qq
    private Bundle params;
    private void shareToQQ(int type, String url,String title,String content){
        params = new Bundle();
        if (type == 0){//分享给QQ好友
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,url);// 内容地址
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,"http://image.daydayrise.net/360@2x.png");// 网络图片地址
            params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQQ(GameRangeActivity.this, params, mIUiListener);
                }
            });
        }else {
            //分享到QQ空间
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,url);// 内容地址
            ArrayList<String> imgUrlList = new ArrayList<>();
            imgUrlList.add("http://image.daydayrise.net/360@2x.png");
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imgUrlList);// 图片地址
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQzone(GameRangeActivity.this, params, mIUiListener);
                }
            });
        }

    }

    private void getData(){
        Log.e("TAG","排名0："+pageindex+"\n");
        if (appid == null){
            return;
        }
        if (isRefresh == true){
            return;
        }
        isRefresh = true;
        Log.e("TAG","排名："+pageindex+"\n");
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.pageindexKey, pageindex+"");
        map.put(APIKey.pagerecordsKey,pagerecords+"");
        map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        String url = "miniapp/"+appid+"/getrange.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {// usersign
            @Override
            public void onSuccess(String data) {

                Log.e("TAG","排名数据："+data+"\n");
                final CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    List<GameRangeModel> l = GsonTools.getGameRangeModel(data);
                    myRangeModel = GsonTools.myRangeModel(data);
                    if (l != null && l.size() > 0){
                        if (l.size() < pagerecords){
                            listview.setPullLoadEnable(false);
                        }
                        list.addAll(l);
                        pageindex += 1;
                        adapter.notifyDataSetChanged();
                    }
                    game_range_button.setText("你排名第"+myRangeModel.getRange()+"位");
                }
                listview.stopLoadMore();
                isRefresh = false;
            }
            @Override
            public void onError(String msg) {
                isRefresh = false;
                listview.stopLoadMore();
            }
        });
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            GameRangeModel model = list.get(position);
            View view=convertView;
            view= LayoutInflater.from(GameRangeActivity.this).inflate(R.layout.game_range_listview_item, null);
            ImageView header = (ImageView) view.findViewById(R.id.game_range_header);
            CircularProgressButton num = (CircularProgressButton) view.findViewById(R.id.game_range_num);
            TextView name = (TextView) view.findViewById(R.id.game_range_name);
            TextView gold = (TextView) view.findViewById(R.id.game_range_gold);
            TextView playlevel = (TextView) view.findViewById(R.id.game_range_playlevel);
            Glide.with(GameRangeActivity.this).load(model.getHeader()).transform(new CircleTransform(GameRangeActivity.this)).dontAnimate().into(header);
            name.setText(model.getNickname());
            gold.setText("金币:"+model.getGoldcount());
            playlevel.setText("关数:"+(model.getPlaylevel()+1));
            if (appid.equals("pkappid")){
                playlevel.setText("Lv."+(model.getPlaylevel()));
            }
            if (position == 0){
                num.setBackgroundColor(getResources().getColor(R.color.limitBackgroundColor));
                num.setStrokeColor(getResources().getColor(R.color.limitBackgroundColor));
                num.setText(""+(position+1));
            }else if (position == 1){
                num.setBackgroundColor(getResources().getColor(R.color.lightGreenColor));
                num.setStrokeColor(getResources().getColor(R.color.lightGreenColor));
                num.setText(""+(position+1));
            }else if (position == 2){
                num.setBackgroundColor(getResources().getColor(R.color.wordBgColor));
                num.setStrokeColor(getResources().getColor(R.color.wordBgColor));
                num.setText(""+(position+1));
            }else {
                num.setBackgroundColor(getResources().getColor(R.color.goldColor));
                num.setStrokeColor(getResources().getColor(R.color.goldColor));
                num.setText(""+(position+1));
            }
            return view;
        }

    }

    // 为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.first_button://分享给微信好友
                    shareToWX(1,url,myRangeModel.getName(),content);
                    break;
                case R.id.second_button://分享到微信朋友圈
                    shareToWX(0,url,myRangeModel.getName(),content);
                    break;
                case R.id.third_button:
                    break;
                default:
                    break;
            }

        }
    };

    //分享到微信
    private void shareToWX(int type,String url,String title,String content){
        //初始化一个WXWebpageObject对象，填写url
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        //用WXWebpageObject对象初始化一个WXMediaMessage对象，填写标题、描述
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = content;
        Bitmap thumb = BitmapFactory.decodeResource(getResources(),R.mipmap.icon);
        msg.thumbData = CommonUtils.bitmapToByteArray(thumb,true);
        //构成一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = msg;
        req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
        CustomApplication.mWxApi.sendReq(req);

    }

    /**
     * 广播接收者
     * @author Gordon
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BroadcastDefine.WX_Share_Result)) {
                //微信分享成功
                getShareGold();
            }
        }
    };

    /**
     * 注册广播
     * @author Gordon
     */
    public void registerBoradcastReceiver(){
        IntentFilter myIntentFilter = new IntentFilter();
        //添加接收广播类型
        myIntentFilter.addAction(BroadcastDefine.WX_Share_Result);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

}
